package com.furongji.education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.furongji.common.domain.vo.CourseOrderVo;
import com.furongji.common.domain.vo.UserOrderVo;
import com.furongji.common.enums.OrderStatusEnum;
import com.furongji.common.exception.MyException;
import com.furongji.common.utils.RedissonLockUtil;
import com.furongji.education.clients.CourseFeignClient;
import com.furongji.education.clients.UserFeignClient;
import com.furongji.education.domain.po.Order;
import com.furongji.education.mapper.OrderMapper;
import com.furongji.education.mq.RabbitOrderProducer;
import com.furongji.education.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author furongji
 * @since 2025-05-29
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private final CourseFeignClient courseClient;

    private final UserFeignClient userClient;

    private final OrderMapper orderMapper;

    private final RabbitOrderProducer rabbitOrderProducer;

    private final RedissonLockUtil redissonLockUtil;

    private static final String LOCK_KEY = "order:lock:";

    @Override
    @Transactional
    public String createOrder(String token, String courseId) {
        UserOrderVo userOrderInfo = userClient.getUserOrderInfo(token);//TODO ThreadLocal获取
        String lock_key = LOCK_KEY + userOrderInfo.getUserId() + ":" + courseId;
        boolean locked = redissonLockUtil.tryLock(lock_key, 0, 20, TimeUnit.SECONDS);
        if (!locked) {
            throw new MyException(200001, "请勿重复下单！");
        }

        try {
            CourseOrderVo courserOrderInfo = courseClient.getCourserOrderInfo(courseId);
            Order order = new Order();
            BeanUtils.copyProperties(courserOrderInfo, order);
            BeanUtils.copyProperties(userOrderInfo, order);
            order.setStatus(OrderStatusEnum.UNPAID);
            super.save(order);
            String orderId = order.getId();

            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    rabbitOrderProducer.sendOrderDelayMessage(orderId);
                }
            });
            return orderId;
        } finally {
            redissonLockUtil.unlock(lock_key);
        }
    }

    // 订单超时取消
    @Override
    public void cancelOrder(String orderId) {
        Order order = super.getById(orderId);
        if (order != null && order.getStatus().equals(OrderStatusEnum.UNPAID)) {
            order.setStatus(OrderStatusEnum.CANCELLED);
            super.updateById(order);
        }
    }

    @Override
    public boolean isPurchaseCourse(String userId, String courseId) {
        LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.eq(Order::getUserId, userId);
        orderWrapper.eq(Order::getCourseId, courseId);
        orderWrapper.eq(Order::getStatus, OrderStatusEnum.PAID);
        long count = super.count(orderWrapper);
        return count > 0;
    }

    @Override
    public Integer orderCount(String date) {
        Integer count = orderMapper.orderCount(date);
        return count;
    }

}
